﻿Imports System.ComponentModel
Imports System.Net
Imports Microsoft.VisualBasic.Logging
Imports Newtonsoft.Json
Imports Microsoft.VisualBasic.FileIO
Imports System.IO
Imports System.Security.Cryptography
Imports System.Text
Imports System.Exception
Imports Newtonsoft.Json.Linq
Imports System.Web
Imports JX3.TencentUpload

Public Class Form1
    Dim dm As New Dm.dmsoft
    Dim loginWidth As Int16 = 1615, loginHeight As Int16 = 851
    Dim jxLoginWin As Long
    Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Integer)

    '    自动换区
    Dim changeAreaBtn As Array = {1442, 164} '登录界面中改变服务器按钮

    Dim ADistance As Short = 25  '大区和服务器之间的距离

    Dim startArea = {530, 313}  '第一个大区的位置
    Dim startServer As Array = {820, 211} '第一个服务器的位置

    Dim areaConfirm As Array = {921, 642}  '选择服务器大区的时候的确定按钮


    Dim entryBtn As Array = {801, 779}  '进入游戏按钮

    Dim jiaoyihangBtn As Array = {136, 228}

    '    交易行
    Dim npcPos As Array = {857, 514} '交易行那个NPC的点击位置

    Dim searchBtn As Array = {681, 237} '交易行中的搜索按钮的位置
    Dim quality As New Dictionary(Of String, Array) '交易行品质下拉菜单
    Dim qualityBtn As Array = {468, 238} '选择品级的下拉列表位置

    Dim firstEquip As Array = {238, 320}  '交易行中第一个装备的位置
    Dim firstEquipYRange As Array = {302, 340} '第一行装备的Y 坐标范围
    Dim equipPriceXRange As Array = {522, 678} '装备价格的X坐标的范围
    Dim equipNameXRange As Array = {213, 325} '装备名字X坐标范围
    Dim lastEquipYRange As Array = {538, 578} '最后一个装备的Y坐标范围

    Dim firstEquipLogoPos As Array = {194, 320} '第一个装备的图标的位置，要把鼠标移上去读取属性  TOADD
    Dim equipXRange As Array = {213, 678} '每一条装备从名字开始位置到当前价格结束位置  TOADD
    Dim attrArea As Array = {208, 10, 440, 580} '属性的区域范围  TOADD

    Dim onePageShowCount As Short = 7 '每一页显示的装备个数
    Dim onePageCount As Short = 0 '初始化为0，这个需要读交易行下面的数字

    Dim onePageFullCount As Short = 50  '根据交易行中的情况，，默认是50， 当然游戏改UI另说2333

    Dim oneGoodAllCount As Short = 0 '交易行底部显示的该类装备的改品级的总数目
    Dim equipHeight As Short = 38 '每一行装备高度
    '    左侧物品类型栏
    Dim oneGoodHeight As Short = 26   '一个物品类的高度，比如 “兵刃”的高度
    Dim firstGood As Array = {63, 278} '第一栏比如兵刃的位置
    Dim goodKind As Array = {}
    Dim priceColor As String = "f3f8f7" '价格处的颜色   普遍的数字都是用的这个颜色
    Dim colorRange As String = "556565" '颜色偏移量大小 （通用的）

    Dim colors As New Dictionary(Of String, String) '珍奇和卓越 装备的颜色

    Dim onePageCountPos As Array = {468, 584, 490, 604} '交易行底部的每页实际数目的数字的坐标  x1  y1  x2  y2  '当左右翻到第三页时要把490变成500 

    Dim oneGoodAllCountPos As Array = {490, 584, 534, 604} '交易行底部显示的该类装备的改品级的总数目的坐标  x1  y1  x2  y2

    Dim onePageScrollUpBtn As Array = {814, 292}
    Dim onePageScrollBtn As Array = {814, 568} '每一页右侧滚动条下边按钮的位置

    Dim nextPageBtnPos As Array = {556, 597}

    '    Dim equip As ArrayList = New ArrayList()  '这是一个装载装备名称和价格信息的  二维数组  ，后面要存入equip表

    Dim equipSeletedBottomColor As String = "b5b788"  '被选中的装备底部的颜色   用来判断滚动条滚动时是否已经翻过一页
    Dim esbcFindArea = {175, 281, 404, 594} '查找被选中的装备的底部颜色的位置的范围

    Dim goodKinds As Array = {1, 2, 3, 4, 5, 7, 8}  ', 2, 3, 4, 5, 7, 8


    Dim isFirstPage As Boolean = True
    Dim lastPageCount As Integer = 0


    '连接数据库相关
    Dim cn As New ADODB.Connection
    Dim rs As New ADODB.Recordset
    '第一个区  第一个服务器
    Dim area As String = "电信七区"
    Dim server As String = "情深似海"

    Dim areaServer As New Dictionary(Of String, Array)

    Dim areas As Array = {"电信七区", "电信八区", "电信一区", "电信二区""电信三区", "电信四区", "电信五区", "电信六区", "电信八区", "网通（一/二）区", "网通三区"}

    Dim startAreaNum As Integer
    Dim startServerNum As Integer

    Dim TencentSign As String

    Dim myEncoder As New UTF8Encoding

    Dim picNum As Integer = 0

    Dim areaNumPub As Integer
    Dim serverNumPub As Integer


    Dim originTime = "1970-01-01 00:00:00"
    Dim appid As Long = 10053455
    Dim bucket As String = "gamepic"
    Dim secretid As String = "AKIDAog21Xn9cTbEMVeVz6otQessB6I9ulJI"
    Dim secretkey As String = "JO1EWBjn2aATcUYGzQ2FycIAc8jpoORh"

    Dim COSAPI_CGI_URL As String = "http://web.file.myqcloud.com/files/v1/"

    Dim tencentUpload As TencentUpload

    Dim priceStr As String
    Dim gold As String
    Dim silver As String
    Dim copper As String

    Dim dataQueue As Queue = New Queue()           '用于存放读到的数据  TOADD
    Dim messageLock As New Object  '用于给操作存储数据的队列加锁的变量  TOADD

    Private Sub init()
        quality.Add("破败", {470, 284})
        quality.Add("普通", {470, 304})
        quality.Add("精巧", {470, 326})
        quality.Add("卓越", {470, 345})
        quality.Add("珍奇", {470, 365})
        quality.Add("稀世", {470, 385})

        colors.Add("珍奇", "f62ef7")
        colors.Add("卓越", "027bf6")

        areaServer.Add("电信七区", {"情深似海", "一苇渡江"})
        ', "快意恩仇", "光明顶", "乱世长安", "不归海", "恋青春", "雪月天枪", "破茧成蝶", "仙侣庭园", "圣火令"
        areaServer.Add("电信八区", {"暗香掠影", "亢龙有悔", "绝代天骄", "战无不胜", "引仙水榭", "百家争鸣"})
        ', "致青春", "侠骨柔情", "星河清梦", "见龙在田", "大明宫", "双龙取水", "龙飞凤舞", "梦回大唐", "武林同庆"
        areaServer.Add("电信一区", {"龙争虎斗", "长安城", "义薄云天"})
        '  "枫华谷", "晴昼海" , "昆仑", "逍遥林", "金水镇", "幽雨坪", "翠烟山", "神龙摆尾", "夜幕星河", "海誓山盟", "龙门荒漠", "扬州城"
        areaServer.Add("电信二区", {"白帝城", "荻花宫"})
        ', "紫薇山", "无盐岛", "三才阵", "侠骨丹心", "演武场", "浮光掠影", "英雄擂", "枫林如火", "风花雪月", "壮志凌云", "肝胆相照", "逍遥游", "云湖天池"
        areaServer.Add("电信三区", {"金蛇漫舞", "秦王殿", "微山书院"})
        ', "青萝山", "无极道场", "忆盈楼", "三星望月", "落雁峰", "飞星遁影", "忆青春", "敬德楼", "双狼之战", "鹤舞九霄", "出神入化", "比翼双飞"
        areaServer.Add("电信四区", {"日月明尊", "蝶恋花", "沁园春", "藏经阁", "燕子坞"})
        ', "战江湖", "午阳岗", "饮马川", "轩辕台", "知节殿", "论剑峰", "六祖台"     (隔了燕子坞) , "少室山", "虎牢关", "飞骏谷"
        areaServer.Add("电信五区", {"乾坤一掷", "幽月轮", "金榜题名", "梦江南", "斗转星移", "唯我独尊", "剑胆琴心", "平步青云", "千岛湖"})
        ', "华山论剑", "圣墓山", "山雨欲来", "笑傲江湖", "如梦令", "枫泾古镇"
        areaServer.Add("电信六区", {"红尘寻梦", "名扬四海"})
        ', "天女散花", "英雄结义", "国色天香", "倾国倾城", "鹰击长空", "众志成城", "烈日斩", "天佑中华", "名动江湖", "剑指龙城", "春和景明", "天马行空", "气吞山河"
        areaServer.Add("网通（一/二）区", {"百转千回", "飞龙在天", "叶芷青", "李忘生"})
        ', "龙战于野", "君山岛", "往生涧", "万马奔腾", "黑云压城", "金风飒飒", "醉舞狂歌", "西京烟雨", "银枪暮雪", "跃马扬鞭", "楼台烟雨"
        areaServer.Add("网通三区", {"飞鸢泛月", "天鹅坪", "五台山", "破阵子"})
        ', "时乘六龙", "纵横江湖", "步月登云", "碧血忠魂", "攻无不克", "君子如风", "侠肝义胆", "念奴娇", "鱼跃龙门", "穆如清风", "行云流水"



        dm.SetDict(1, "number.txt")

        dm.SetMouseDelay("normal", 200)
        dm.SetMouseDelay("windows", 200)
        dm.SetMouseDelay("dx", 200)
        dm.SetMouseDelay("windows3", 200)


        dm.SetKeypadDelay("normal", 300)
        dm.SetKeypadDelay("windows", 300)

        dm.SetKeypadDelay("dx", 300)

        initDatabaseConnection()

        tencentUpload = New TencentUpload(appid, secretid, secretkey)


        
        Dim fileStream = New FileStream("record.txt", FileMode.Open, FileAccess.Read)
        Dim midByte As Byte() = New Byte(fileStream.Length - 1) {}
        fileStream.Read(midByte, 0, fileStream.Length)
        Dim endStr As String = Encoding.UTF8.GetString(midByte)
        fileStream.Close()
        If endStr = "" Then
            startAreaNum = 0
            startServerNum = 0
        Else
            Dim asArr As String() = endStr.Split(" ")
            startAreaNum = CInt(asArr(2))
            startServerNum = CInt(asArr(3))
        End If
        
    End Sub
    '    读取列表中显示的七项设备   TOADD
    Private Sub readOnePage(nameColor As String)
        dm.UseDict(1)
        For i As Integer = 0 To onePageShowCount - 1
            dm.SetWindowState(jxLoginWin, 1)
            Dim a As Array
            Dim middleX As New ArrayList
            Dim nowEquipY = {firstEquipYRange(0) + equipHeight * i, firstEquipYRange(1) + equipHeight * i}
            '这个是现在的只截图，截取从名字到价格和属性两张图并且进行二值化处理后再传到腾讯云
            Dim current = Now
            Console.WriteLine(current)
            Dim unixTimeStr = CStr(tencentUpload.ToUnixTime(current))
            Dim picName As String = "jx3" + "-" + unixTimeStr + "-" + "equip" + CStr(picNum)
            Dim picAttr As String = "jx3" + "-" + unixTimeStr + "-" + "attr" + CStr(picNum)
            If dm.Capture(equipXRange(0), nowEquipY(0), equipXRange(1), nowEquipY(1), picName + ".bmp") <> 1 Then
                Console.WriteLine(picName + "  failed")
                Continue For
            End If
            MoveTo(firstEquipLogoPos(0), firstEquipLogoPos(1) + equipHeight * i)
            randSleep(300)
            If dm.Capture(attrArea(0), attrArea(1), attrArea(2), attrArea(3), picAttr + ".bmp") <> 1 Then
                Console.WriteLine(picAttr + "  failed")
                Continue For
            End If
            MoveTo(1000, 390)
            
            '把数据插入到队列中
            SyncLock messageLock
                dataQueue.Enqueue("剑侠情缘3|" + area + "|" + server + "|" + picName + "|" + picAttr)
            End SyncLock
            Console.WriteLine("剑侠情缘3|" + area + "|" + server + "|" + picName + "|" + picAttr)
            '这个是之前读取名字特征码和装备价格的方法
            '            dm.SetWindowState(jxLoginWin, 1)
            '            Dim nameStr As String = dm.FetchWord(equipNameXRange(0), nowEquipY(0), equipNameXRange(1), nowEquipY(1), colors.Item(nameColor) + "-" + colorRange, "*")
            '            Dim current = Now
            '            Console.WriteLine(current)
            '            Dim unixTimeStr = CStr(tencentUpload.ToUnixTime(current))
            '            Dim picName As String = "jx3" + "-" + unixTimeStr + "-" + "equip" + CStr(picNum) + ".bmp"
            '            If dm.Capture(equipNameXRange(0), nowEquipY(0), equipNameXRange(1), nowEquipY(1), picName) <> 1 Then
            '                Continue For
            '            End If
            '            picNum = picNum + 1
            '            a = FindPic(equipPriceXRange(0), nowEquipY(0), equipPriceXRange(1), nowEquipY(1), "goldblock.bmp", colorRange, 20, 0)
            '            If a(0) = -1 Then
            '                Continue For
            '            End If
            '            middleX.Add(a(0))
            '            a = FindPic(equipPriceXRange(0), nowEquipY(0), equipPriceXRange(1), nowEquipY(1), "jinyuanbao.bmp", colorRange, 20, 0)
            '            '            现在图片识别失败因此中间的通过picX picY把金币价格分成
            '            If a(0) = -1 Then
            '                Continue For
            '            End If
            '            middleX.Add(a(0))
            '            
            '            gold = dm.Ocr(equipPriceXRange(0), nowEquipY(0), middleX.Item(0), nowEquipY(1), priceColor + "-" + colorRange, 0.8)
            '            silver = dm.Ocr(middleX.Item(0), nowEquipY(0), middleX.Item(1), nowEquipY(1), priceColor + "-" + colorRange, 0.8)
            '            copper = dm.Ocr(middleX.Item(1), nowEquipY(0), equipPriceXRange(1), nowEquipY(1), priceColor + "-" + colorRange, 0.8)
            '            '            equip.Add({nameStr, gold, silver, copper, picName})
            '            '读一条上传一条数据
            '            Dim time = Format(current, "yyyy-MM-dd HH:mm:ss")
            '            Dim priceStr As String = gold + "金" + silver + "银" + copper + "铜"
            '            Dim pictureUrl As String
            '            Dim picUpRes As JObject = JsonConvert.DeserializeObject(tencentUpload.UploadFile(bucket, "/" + picName, picName))
            '            Dim code As String = picUpRes("code")
            '            Dim message As String = picUpRes("message")
            '            If code = "0" And message = "SUCCESS" Then
            '                pictureUrl = picUpRes("data")("access_url").ToString()
            '            Else
            '                pictureUrl = ""
            '            End If
            '            Dim postDataStr As String = "binary_image=" + nameStr + "&game=剑侠情缘网络版三" + "&area=" + area + "&server=" + server + "&price=" + priceStr + "&time=" + time + "&picture=" + picName
            '            sendEquip("https://api.unique0lai.cn/inner_data/game_data/", postDataStr)
        Next
        Return
    End Sub

    Private Sub postData()   'TOADD
        Dim flag As Boolean
        While True
            Dim data As String = ""

            SyncLock messageLock
                If dataQueue.Count <> 0 Then
                    Console.WriteLine("队列中数目：" + dataQueue.Count.ToString())
                    data = dataQueue.Dequeue()
                    flag = True
                Else
                    flag = False
                End If
            End SyncLock

            If Not flag Then
                Continue While
            End If
            '"game=剑侠情缘3" + "&area=" + area + "&server=" + server + "&picture=" + picName + ".gif," + picAttr + ".gif"
            Dim str() As String = Split(data, "|") '{游戏名，区，服，名称图片，属性图片}
            Binaryzation(str(3) + ".bmp", str(3) + ".gif")
            Binaryzation(str(4) + ".bmp", str(4) + ".gif")
            tencentUpload.UploadFile("gamepic", "/" + str(3) + ".gif", str(3) + ".gif")
            tencentUpload.UploadFile("gamepic", "/" + str(4) + ".gif", str(4) + ".gif")
            Dim postDataStr As String = "game=" + str(0) + "&area=" + str(1) + "&server=" + str(2) + "&pic=" + str(3) + ".gif," + str(4) + ".gif"
            sendEquip("https://api.unique0lai.cn/inner_data/data_pic/", postDataStr)
            Console.WriteLine("post data success!")
        End While

    End Sub

    '    每一页的向下滚动
    Function scrollInOnePage(i As Integer) As Integer
        dm.SetWindowState(jxLoginWin, 1)
        MoveTo(813, 525)
        LeftClick()
        '        dm.WheelUp()
        MoveTo(onePageScrollBtn(0), onePageScrollBtn(1))
        Dim w As Integer

        If i = 5 Then
            w = 26
        ElseIf i = 6 Then
            w = 33
        Else
            w = 27
        End If
        While w
            LeftClick()
            w = w - 1
        End While
        Return 0
    End Function

    Function toTop() As Integer
        For c As Short = 0 To 30
            MoveTo(812, 302)
            LeftClick()
        Next
        MoveTo(onePageScrollUpBtn(0), onePageScrollUpBtn(1))
        For upclick As Integer = 0 To 12
            LeftClick()
        Next
        Return 1
    End Function

    '左右翻页函数  其实主要的控制代码都在这里

    Function turnPage() As Integer
        dm.UseDict(1)
        '        这个是确定要翻几页，点击翻页按钮
        Dim turnPageCount As Integer
        '        Dim upCount As Short = Int(20 * (50 / CSng(numberAfterLine - lastPageCount))) + 1
        oneGoodAllCount = Integer.Parse(dm.Ocr(oneGoodAllCountPos(0), oneGoodAllCountPos(1), oneGoodAllCountPos(2), oneGoodAllCountPos(3), priceColor + "-" + colorRange, 0.8))
        If oneGoodAllCount > onePageFullCount Then
            turnPageCount = Int(oneGoodAllCount / onePageFullCount) + 1
        Else
            turnPageCount = 1
        End If
        If turnPageCount > 1 Then
            For j As Integer = 1 To turnPageCount
                If j >= 3 Then
                    onePageCountPos(2) = 500
                Else
                    onePageCountPos(2) = 490
                End If

                scrollRead()
                dm.SetWindowState(jxLoginWin, 1)
                If j < turnPageCount Then
                    MoveTo(nextPageBtnPos(0), nextPageBtnPos(1))
                    LeftClick()
                    '滚动滚动条到顶部
                    toTop()
                End If
            Next
        Else
            scrollRead()
        End If

        Return 0
    End Function

    Function scrollRead() As Integer
        If oneGoodAllCount >= 1000 Then
            onePageCountPos(0) = 460
        Else
            onePageCountPos(0) = 468
        End If

        Dim scrollCount As Integer '确定每一整页有几页需要滚动（并不是准确的每页滚动几次）
        Dim lastShowCount As Integer '最后一页装备个数（目前是默认不读最后一页，所以就没什么用）
        Dim numberAfterLine As Integer = Integer.Parse(dm.Ocr(onePageCountPos(0), onePageCountPos(1), onePageCountPos(2), onePageCountPos(3), priceColor + "-" + colorRange, 0.8))

        If isFirstPage Then
            onePageCount = numberAfterLine
            isFirstPage = False
        Else
            onePageCount = numberAfterLine - lastPageCount
        End If
        If onePageCount > onePageShowCount Then
            scrollCount = Int(onePageCount / onePageShowCount) + 1
            lastShowCount = onePageCount Mod onePageShowCount
        Else
            scrollCount = 1
        End If
        lastPageCount = lastPageCount + onePageCount
        If scrollCount > 1 Then
            For i As Integer = 1 To scrollCount - 1
                readOnePage("珍奇")
                If i < scrollCount - 1 Then
                    scrollInOnePage(i)
                End If
            Next
        Else
            readOnePage("珍奇")
        End If
        Return 0
    End Function

    '    左侧物品类型的更换（ 兵器，暗器，服饰）

    Function changeGoods(goodKind As Integer) As Integer
        '        选择左侧物品类型（这回把大类中的小类的列表打开，后面读完数据还要关上）
        MoveTo(firstGood(0), firstGood(1) + oneGoodHeight * (goodKind - 1))
        LeftClick()
        '        打开品级列表
        MoveTo(qualityBtn(0), qualityBtn(1))
        LeftClick()
        '        选择品级
        Dim targetPos As Array = quality.Item("珍奇")
        MoveTo(targetPos(0), targetPos(1))
        LeftClick()

        '        点击搜索
        MoveTo(searchBtn(0), searchBtn(1))
        LeftClick()


        '        点完搜索按钮出现的应该是当前类型物品的第一页
        isFirstPage = True
        lastPageCount = 0
        toTop()
        Return 0
    End Function


    '该函数用在每个服务器进来打开拍卖行之后
    Private Sub readOneServer()
        For goodkind As Integer = 0 To goodKinds.Length - 1
            changeGoods(goodKinds(goodkind))

            randSleep(1000)
            turnPage() ' 主要的逻辑控制代码

            '读完之后把打开的物品类别的子菜单关闭
            MoveTo(firstGood(0), firstGood(1) + oneGoodHeight * goodkind)
            LeftClick()
        Next
    End Sub

    Private Sub randSleep(i As Integer)
        Randomize()
        i = Int(Rnd() * i + i) / 2
        Sleep(i)
    End Sub


    Function hwnd(className As String, title As String, state As Int16) As Long
        Dim hwnd1 As Long
        hwnd1 = dm.FindWindow(className, title)
        If hwnd1 <= 0 Then
            MsgBox("查找登录界面失败")
            Return 0
        End If
        If dm.BindWindowEx(hwnd1, "normal", "windows3", "windows", "", 0) <> 1 Then
            MsgBox("绑定登录界面失败")
            Return 0
        End If
        If dm.SetWindowState(hwnd1, state) <> 1 Then
            MsgBox("激活登录界面失败")
            Return 0
        End If
        hwnd = hwnd1
    End Function

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        '        Dim jxUpdateWin As Long

        '        jxUpdateWin = dm.FindWindow("JX3Gameupdater", "剑网3更新程序")
        '        If jxUpdateWin <= 0 Then
        '            MsgBox("查找更新界面失败")
        '            Return
        '        End If
        '        If dm.BindWindow(jxUpdateWin, "dx2", "windows3", "windows", 0) <> 1 Then
        '            MsgBox("绑定更新界面失败")
        '            Return
        '        End If
        '        If dm.SetWindowState(jxUpdateWin, 1) <> 1 Then
        '            MsgBox("激活更新界面失败")
        '            Return
        '        End If
        '        randSleep(1000)
        '        If dm.MoveTo(1062, 574) <> 1 Then
        '            MsgBox("鼠标移动失败")
        '            Return
        '        End If
        '
        '        If dm.LeftClick() <> 1 Then
        '            MsgBox("鼠标点击失败")
        '            Return
        '        End If



        jxLoginWin = hwnd("KGWin32App", "剑侠情缘网络版叁 - 情深似海 @ 电信七区", 1)
        If dm.SetWindowSize(jxLoginWin, loginWidth, loginHeight) <> 1 Then
            MsgBox("设置登录界面大小失败")
            Return
        End If


        '        randSleep(10000)
        '        If dm.MoveTo(816, 409) <> 1 Then
        '            MsgBox("鼠标移动失败")
        '            Return
        '        End If
        '        If dm.LeftClick() <> 1 Then
        '            MsgBox("鼠标点击失败")
        '            Return
        '        End If
        '
        '        If dm.SendString(jxLoginWin, "ZhWy197531") <> 1 Then
        '            MsgBox("输入密码失败")
        '            Return
        '        End If
        '        randSleep(3000)
        '        If dm.MoveTo(850, 470) <> 1 Then
        '            MsgBox("鼠标移动失败")
        '            Return
        '        End If
        '        If dm.LeftClick() <> 1 Then
        '            MsgBox("鼠标点击失败")
        '            Return
        '        End If





        '       这是查找创建角色按钮来确定进入了角色选择界面
        '        MsgBox("进入循环查找创建角色图片")
        '        Dim c As Boolean = True
        '        randSleep(8000)
        '        While c
        '            randSleep(5000)
        '            Dim picX, picY As Long
        '            Dim picfind As Int16 = dm.FindPic(1377, 498, 1508, 534, "create.bmp", "040404", 0.5, 1, picX, picY)
        '            If picfind <> -1 Then
        '                MsgBox("已经进入选择角色界面")
        '                dm.KeyPress(13)
        '                c = False
        '            End If
        '        End While



        '        If dm.MoveTo(805, 806) <> 1 Then
        '            MsgBox("鼠标移动失败")
        '            Return
        '        End If
        '        If dm.LeftClick() <> 1 Then
        '            MsgBox("鼠标点击失败")
        '            Return
        '        End If


        '        查找血条图片确定进入了主页
        '        Dim d As Boolean = True
        '        While d
        '            randSleep(5000)
        '            Dim picX, picY As Long
        '            Dim picfind As Int16 = dm.FindPic(0, 0, 395, 104, "end.bmp", "040404", 0.5, 1, picX, picY)
        '            If picfind <> -1 Then
        '                MsgBox("已经进入游戏界面")
        '                randSleep(1000)
        '                If dm.MoveTo(1156, 178) <> 1 Then
        '                    MsgBox("鼠标移动失败")
        '                    Return
        '                End If
        '                If dm.LeftClick() <> 1 Then
        '                    MsgBox("鼠标点击失败")
        '                    Return
        '                End If
        '                randSleep(2000)
        '
        '                If dm.KeyPressChar("F") <> 1 Then
        '                    MsgBox("按F打开交易行菜单失败")
        '                    Return
        '                End If
        '                d = False
        '            End If
        '        End While


        openTrade()

        '        dm.UnBindWindow()
    End Sub

    Function openTrade() As Integer
        dm.SetWindowState(jxLoginWin, 1)
        Dim picX, picY As Long
        Dim a As Boolean = True
        Dim picfind As Integer
        While a
            picfind = dm.FindPic(0, 0, 395, 104, "end.bmp", "040404", 0.8, 1, picX, picY)
            If picfind <> -1 Then
                a = False
            End If
            randSleep(5000)
        End While
        randSleep(10000)
        If picfind <> -1 Then
            randSleep(1000)
            '            移动鼠标关闭广告
            If dm.MoveTo(1156, 178) <> 1 Then
                MsgBox("鼠标移动失败")
                Return 0
                Exit Function
            End If
            If dm.LeftClick() <> 1 Then
                MsgBox("鼠标点击失败")
                Return 0
                Exit Function
            End If


            If dm.MoveTo(npcPos(0), npcPos(1)) <> 1 Then
                MsgBox("鼠标移动失败")
                Return 0
                Exit Function
            End If
            Dim m As Boolean = True
            Dim picFindCount As Integer = 20
            While m And picFindCount
                If dm.RightClick() <> 1 Then
                    MsgBox("右键NPC打开交易行菜单失败")
                    Return 0
                    Exit Function
                End If
                If dm.FindPic(64, 217, 105, 257, "end.bmp", "040404", 0.5, 1, picX, picY) <> -1 Then
                    m = False
                End If
                picFindCount = picFindCount - 1

                randSleep(1000)
            End While

            If m Then
                Return 0
                Exit Function
            End If

        End If
        randSleep(1000)

        If picfind Then

        End If


        '        dm.MoveTo(136, 238)
        If dm.MoveTo(jiaoyihangBtn(0), jiaoyihangBtn(1)) <> 1 Then
            MsgBox("鼠标移动失败")
            Return 0
            Exit Function
        End If
        If dm.LeftClick() <> 1 Then
            MsgBox("鼠标点击失败")
            Return 0
            Exit Function
        End If
        Return 1
    End Function


    Private Sub updateWin()
        Dim jxUpdateWin As Long
        jxUpdateWin = dm.FindWindow("JX3Gameupdater", "剑网3更新程序")
        If jxUpdateWin <= 0 Then
            MsgBox("查找更新界面失败")
            Return
        End If
        If dm.BindWindow(jxUpdateWin, "dx2", "windows3", "windows", 0) <> 1 Then
            MsgBox("绑定更新界面失败")
            Return
        End If
        If dm.SetWindowState(jxUpdateWin, 1) <> 1 Then
            MsgBox("激活更新界面失败")
            Return
        End If
        randSleep(1000)
        If dm.MoveTo(1062, 574) <> 1 Then
            MsgBox("鼠标移动失败")
            Return
        End If

        If dm.LeftClick() <> 1 Then
            MsgBox("鼠标点击失败")
            Return
        End If
    End Sub

    Dim passwordInput As Array = {816, 401}
    Dim loginBtn As Array = {850, 456}
    Function login() As Short


        '        移动鼠标到密码输入框
        If dm.MoveTo(passwordInput(0), passwordInput(1)) <> 1 Then
            MsgBox("鼠标移动失败")
            Return 0
            Exit Function
        End If
        If dm.LeftClick() <> 1 Then
            MsgBox("鼠标点击失败")
            Return 0
            Exit Function
        End If
        randSleep(1500)
        '        输入密码
        If dm.SendString(jxLoginWin, "197531qwer") <> 1 Then
            MsgBox("输入密码失败")
            Return 0
            Exit Function
        End If
        randSleep(1000)
        '        鼠标移动到登录按钮处
        If dm.MoveTo(loginBtn(0), loginBtn(1)) <> 1 Then
            MsgBox("鼠标移动失败")
            Return 0
            Exit Function
        End If
        If dm.LeftClick() <> 1 Then
            MsgBox("鼠标点击失败")
            Return 0
            Exit Function
        End If

        Return 1
    End Function

    Private Sub loginWin()
        Dim b As Boolean = True
        While b
            randSleep(5000)
            jxLoginWin = dm.FindWindow("KGWin32App", "剑侠情缘网络版叁 - 绝代天骄 @ 电信八区")
            If jxLoginWin > 0 Then
                dm.UnBindWindow()
                '                MsgBox("已经找到登录界面")
                b = False
            End If
        End While
        '        MsgBox("进入登录界面")
        If dm.BindWindow(jxLoginWin, "dx2", "windows3", "windows", 0) <> 1 Then
            MsgBox("绑定登录界面失败")
            Return
        End If
        If dm.SetWindowState(jxLoginWin, 1) <> 1 Then
            MsgBox("激活登录界面失败")
            Return
        End If
        If dm.SetWindowSize(jxLoginWin, loginWidth, loginHeight) <> 1 Then
            MsgBox("设置登录界面大小失败")
            Return
        End If

    End Sub

    Private Sub chooseChara()
        '        Dim c As Boolean = True
        '        MsgBox("进入循环查找创建角色图片")
        '        While c
        '            randSleep(5000)
        '            Dim picX, picY As Long
        '            Dim picfind As Int16 = dm.FindPic(1377, 498, 1508, 534, "create.bmp", "040404", 0.5, 1, picX, picY)
        '            If picfind <> -1 Then
        '                MsgBox("已经进入选择角色界面")
        '                dm.KeyPress(13)
        '                c = False
        '            End If
        '        End While

        If dm.MoveTo(entryBtn(0), entryBtn(1)) <> 1 Then
            MsgBox("鼠标移动失败")
            Return
        End If
        If dm.LeftClick() <> 1 Then
            MsgBox("鼠标点击失败")
            Return
        End If
    End Sub
    Private Sub MoveTo(x As Double, y As Double)
        If dm.MoveTo(x, y) <> 1 Then
            MsgBox("鼠标移动失败")
            Return
        End If
    End Sub

    Private Sub LeftClick()
        If dm.LeftClick() <> 1 Then
            MsgBox("鼠标点击失败")
            Return
        End If
    End Sub

    Private Sub funcQuitGame()
        dm.SetWindowState(jxLoginWin, 1)
        OpenSetting(dm)
        randSleep(1500)
        MoveTo(789, 537)
        LeftClick()
        randSleep(1000)
        MoveTo(732, 374)
        LeftClick()
    End Sub

    Private Sub quit_Click(sender As Object, e As EventArgs) Handles quit.Click
        funcQuitGame()
    End Sub

    Private Sub OpenSetting(dm As Object)
        If dm.MoveTo(1579, 781) <> 1 Then
            MsgBox("鼠标移动失败")
            Return
        End If
        If dm.LeftClick() <> 1 Then
            MsgBox("鼠标点击失败")
            Return
        End If
    End Sub

    Private Sub funcGoToLogin()
        dm.SetWindowState(jxLoginWin, 1)
        OpenSetting(dm)
        randSleep(1500)
        MoveTo(800, 480)
        LeftClick()
        randSleep(1000)
        MoveTo(732, 374)
        LeftClick()
    End Sub

    Private Sub gotoLogin_Click(sender As Object, e As EventArgs) Handles gotoLogin.Click
        funcGoToLogin()
    End Sub

    Private Sub funcGoToChoose()
        dm.SetWindowState(jxLoginWin, 1)
        OpenSetting(dm)
        randSleep(1500)
        MoveTo(800, 506)
        LeftClick()
        randSleep(1000)
        MoveTo(732, 374)
        LeftClick()
    End Sub

    Private Sub gotoChoose_Click(sender As Object, e As EventArgs) Handles gotoChoose.Click
        funcGoToChoose()
    End Sub

    Private Sub active_Click(sender As Object, e As EventArgs) Handles active.Click
        jxLoginWin = hwnd("KGWin32App", "剑侠情缘网络版叁 - 绝代天骄 @ 电信八区", 1)
        If dm.SetWindowSize(jxLoginWin, loginWidth, loginHeight) <> 1 Then
            MsgBox("设置登录界面大小失败")
            Return
        End If
    End Sub



    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        init()
    End Sub

    Function FindPic(x1 As Short, y1 As Short, x2 As Short, y2 As Short, picname As String, colorRange As String, findCount As Integer, interval As Integer) As Array
        Dim a As Boolean = True
        Dim b As Short
        Dim count = findCount
        Dim picX As Short, picY As Short
        While a And count > 0
            b = dm.FindPic(x1, y1, x2, y2, picname, colorRange, 0.8, 1, picX, picY)
            If b <> -1 Then
                dm.SetWindowState(jxLoginWin, 1)
                a = False
                Return {picX, picY}
            End If
            count = count - 1
            If interval <> 0 Then
                randSleep(interval)
            End If
        End While
        Return {-1}
        Exit Function
    End Function

    Function selectServer(areaNum As Integer, serverNum As Integer) As Integer
        '        Dim a As Array = FindPic(1356, 140, 1541, 190, "changeServerBtn.bmp", "040404", 10)
        '        '        Dim a As Array = FindPic(6, 730, 77, 810, "jinshan.bmp", "040404")
        '        If a(0) <> -1 Then
        '            MoveTo(a(0) + 20, a(1) + 8)
        '        Else
        '            MoveTo(changeAreaBtn(0), changeAreaBtn(1))
        '        End If
        '        LeftClick()


        Dim a As Array = FindPic(6, 730, 77, 810, "jinshan.bmp", "040404", 50, 2500)
        If a(0) <> -1 Then
        Else
            MsgBox("未找到")
            Return 0
            Exit Function
        End If
        dm.SetWindowState(jxLoginWin, 1)


        MoveTo(changeAreaBtn(0), changeAreaBtn(1))
        LeftClick()

        '        选择大区并点击
        MoveTo(startArea.getValue(0), startArea.getValue(1) + ADistance * areaNum)
        LeftClick()
        '        选择服务器并点击
        MoveTo(startServer.GetValue(0), startServer.GetValue(1) + ADistance * serverNum)
        LeftClick()

        '        点击确定按钮
        MoveTo(areaConfirm(0), areaConfirm(1))
        LeftClick()
        Return 1
    End Function

    Private Sub changeServer_Click(sender As Object, e As EventArgs) Handles changeServer.Click
        dm.SetWindowState(jxLoginWin, 1)
        Dim areaNum As Short = Integer.Parse(AreaBox.Text)
        Dim serverNum As Short = Integer.Parse(ServerBox.Text)
        funcGoToLogin()
        Dim picX = 0, picY = 0
        Dim a As Array = FindPic(1356, 140, 1541, 190, "changeServerBtn.bmp", "040404", 20, 2500)
        If a(0) <> -1 Then
            MsgBox("找到更改服务器按钮")
            dm.SetWindowState(jxLoginWin, 1)
            MoveTo(changeAreaBtn.GetValue(0), changeAreaBtn.GetValue(1))
        Else
            MsgBox("未找到更改服务器按钮")
            dm.SetWindowState(jxLoginWin, 1)
            MoveTo(changeAreaBtn.GetValue(0), changeAreaBtn.GetValue(1))

        End If

        LeftClick()

        randSleep(1000)
        '        选择大区并点击
        MoveTo(startArea.getValue(0), startArea.getValue(1) + ADistance * areaNum)
        LeftClick()
        '        选择服务器并点击
        MoveTo(startServer.GetValue(0), startServer.GetValue(1) + ADistance * serverNum)
        LeftClick()

        '        点击确定按钮
        MoveTo(areaConfirm(0), areaConfirm(1))
        LeftClick()

        login()
    End Sub

    Private Sub loginbutton_Click(sender As Object, e As EventArgs) Handles loginbutton.Click
        dm.SetWindowState(jxLoginWin, 1)
        login()
    End Sub


    Private Sub initDatabaseConnection()
        Dim db_host As String
        Dim db_user As String
        Dim db_pass As String
        Dim db_data As String
        Dim strCn As String
        db_host = "localhost" '"5730412e3f865.sh.cdb.myqcloud.com" 'localhost
        db_user = "root"    '"root"   '用户名  
        db_pass = "root" '"root" '用户密码  
        db_data = "jx3" '"jx3"  '数据库名 
        strCn = "DRIVER={MySQL ODBC 5.3 Unicode Driver};" & _
                "SERVER=" & db_host & ";" & _
                "DATABASE=" & db_data & ";" & _
                "UID=" & db_user & ";PWD=" & db_pass & ";" & _
                "OPTION=3;stmt=SET NAMES GB2312"
        ' 连接数据库  
        '        cn.Open(strCn)
    End Sub


    '插入数据到剑网三本地数据库
    Private Sub insertData(area As String, server As String, equipment As String, gold As String, silver As String, copper As String)
        Dim sqlStr As String = "insert into game_info (game,area,server,equipment,gold,silver,copper) values('" + "剑侠情缘网络版三" + "','" + area + "','" + server + "','" + equipment + "'," + gold + "," + silver + "," + copper + ")"
        '        Dim sql As String = "insert into game_info (game,area,server,equipment,gold,silver,copper) values(" + "'剑侠情缘网络版三'" + ",'" + area + "','" + server + "','" + equipment + "'," + gold + "," + silver + "," + copper + ")"
        cn.Execute(sqlStr)
    End Sub
    '链接dnf云数据库
    Private Sub connectCloudDatabase(str As String)

        Dim cn As New ADODB.Connection
        Dim rs As New ADODB.Recordset

        Dim sql As String


        cn.ConnectionString = "DRIVER={MySQL ODBC 5.3 Unicode Driver}; " _
                          & " Password=system123; " _
                          & " Persist Security Info=True; " _
                          & " User ID=root; " _
                          & " Server=5732eb9c243f0.sh.cdb.myqcloud.com;" _
                          & " Port=6647;" _
                          & " DataBase=fromumu; " _
                          & " OPTION=0"
        cn.Open()
        sql = "insert into dnf values(null," + str + ",0)"
        cn.Execute(sql)
        cn.Close()
    End Sub



    Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
        dm.SetWindowState(jxLoginWin, 1)
        changeGoods(1)
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        readOnePage("珍奇")
    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Dim startTxt As String = "电信七区 情深似海 1 1"
        Dim startByte As Byte() = Encoding.UTF8.GetBytes(startTxt)
        Dim inputStream As Stream = New FileStream("test.txt", FileMode.Open, FileAccess.Write)
        inputStream.Write(startByte, 0, startByte.Length)
        inputStream.Close()
        Dim fileStream = New FileStream("test.txt", FileMode.Open, FileAccess.Read)
        Dim midByte As Byte() = New Byte(fileStream.Length - 1) {}
        fileStream.Read(midByte, 0, fileStream.Length)
        Dim endStr As String = Encoding.UTF8.GetString(midByte)
        fileStream.Close()
        Dim arr As String() = endStr.Split(" ")
        MsgBox(arr(0))
    End Sub

    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
        turnPage()
    End Sub

    Function sendEquip(url As String, postData As String) As Integer
        Dim HttpClient = CreateObject("Microsoft.XMLHTTP")
        HttpClient.Open("POST", url, False)
        HttpClient.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
        HttpClient.setRequestHeader("Authorization", "token vrthefuture")
        HttpClient.Send(postData)
        '        MsgBox(HttpClient.Status)


        Do While HttpClient.readyState <> 4
            If HttpClient.Status <> 200 Then
                MsgBox(HttpClient.responseText)
                randSleep(2000)
            End If
        Loop


        Return 0
    End Function

    Function setArea(areaNum As Integer) As Integer
        area = areas(areaNum)
        areaNumPub = areaNum
        Return 1
    End Function
    Function setServer(serverNum) As Integer
        serverNumPub = serverNum
        server = areaServer.Item(area)(serverNum)
        Return 1
    End Function


    Function funcAutoGet() As Integer
        updateWin()
        loginWin()
        '        startAreaNum
        'areas.Length-1

        Dim thread1 As New Threading.Thread(AddressOf postData)  'TOADD
        Dim thread2 As New Threading.Thread(AddressOf postData)
        thread1.Start()
        thread2.Start()

        For areaNum As Integer = 1 To 1
            setArea(areaNum)
            '            startServerNum
            'areaServer.Item(area).Length-1
            For serverNum As Integer = 2 To 2
                setServer(serverNum)
                Dim selectRes As Integer
                If areaNum = 5 And serverNum = 4 Then
                    selectRes = selectServer(areaNum, serverNum + 7)
                Else
                    selectRes = selectServer(areaNum, serverNum)
                End If
                If selectRes <> 1 Then
                    Continue For
                End If
                dm.SetWindowState(jxLoginWin, 1)
                randSleep(1000)
                Dim loginRes As Integer
                loginRes = login()
                If loginRes <> 1 Then
                    MsgBox("登录失败")
                End If

                randSleep(6000)
                chooseChara()

                If openTrade() <> 1 Then
                    funcGoToChoose()
                    Continue For
                End If
                dm.SetWindowState(jxLoginWin, 1)
                randSleep(1500)
                readOneServer()
                funcGoToLogin()
                picNum = 0
            Next
        Next
        Dim endFlag = True

        While endFlag   'TOADD
            If dataQueue.Count = 0 Then
                endFlag = False
                Console.WriteLine("所有图片以及装备数据上传完毕")
                thread1.Abort()
                thread2.Abort()
            End If
            randSleep(2000)
        End While


    End Function

    '这里貌似需要从第一个区的第一个服开始读才行
    Private Sub autoget_Click(sender As Object, e As EventArgs) Handles autoget.Click
        funcAutoGet()

    End Sub

    Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
        '        dm.SetWindowState(jxLoginWin, 1)
        '        Dim a As Array = FindPic(1356, 140, 1541, 190, "changeServerBtn.bmp", "040404")
        '        Dim a As Array = FindPic(6, 730, 77, 810, "jinshan.bmp", "040404")
        Dim s As Integer = 10
        Return
    End Sub

    Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
        dm.SetWindowState(jxLoginWin, 1)
        readOneServer()
        '        For equipNum As Integer = 0 To equip.Count - 1
        '            Dim currentEquip As Array = equip(equipNum)
        '            Dim time = Format(Now, "yyyy-MM-dd HH:mm:ss")
        '            Dim postData As Object = currentEquip
        '            Dim priceStr As String = currentEquip(1) + "金" + currentEquip(2) + "银" + currentEquip(3) + "铜"
        '            Dim postDataStr As String = "binary_image=" + currentEquip(0) + "&game=剑侠情缘网络版三" + "&area=" + area + "&server=" + server + "&price=" + priceStr + "&time=" + time
        '            '                    If Not currentEquip(2) Then
        '            '
        '            '                        Continue For
        '            '                    End If
        '
        '            sendEquip("https://api.unique0lai.cn/inner_data/game_data/", postDataStr)
        '        Next
        funcGoToLogin()
    End Sub

    Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click
        insertData("aweras", "asdfsd", "asdgethyjhdt", 90, 12, 34)
    End Sub


    



    Private Sub Button9_Click(sender As Object, e As EventArgs) Handles Button9.Click
        '        Console.WriteLine("aaa" + Chr(13) + Chr(10) + "bbb")
        '        Dim current = Now
        '        Dim unixTimeStr = CStr(tencentUpload.ToUnixTime(current))
        '        Dim picName As String = "jx3" + "-" + unixTimeStr + "-" + "equip" + CStr(2)
        '        Dim b As JObject = JsonConvert.DeserializeObject(tencentUpload.UploadFile(bucket, "/" + picName, "aaa.bmp"))
        '        Dim code As String = b("code").ToString()
        '        Dim message As String = b("message").ToString()
        '        If code = "0" And message = "SUCCESS" Then
        '            Dim a As String = b("data")("access_url").ToString()
        '            Console.WriteLine(a)
        '        End If

        Dim epoch = (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000
        Dim current = Now
        Dim unixTimeStr = CStr(tencentUpload.ToUnixTime(current))



        Return

    End Sub

    Private Sub Button10_Click(sender As Object, e As EventArgs) Handles Button10.Click
        dm.SetWindowState(jxLoginWin, 1)
        MoveTo(firstEquipLogoPos(0), firstEquipLogoPos(1))

        randSleep(1000)
        If dm.Capture(attrArea(0), attrArea(1), attrArea(2), attrArea(3), "qwerasdf" + ".bmp") <> 1 Then
            Console.WriteLine("qwerasdf" + "  failed")
        End If
        Binaryzation("qwerasdf" + ".bmp", "qwerasdf" + ".gif")

    End Sub

    '简单二值化图片信息，参数：待处理图片路径，处理后图片路径.gif   TOADD
    Public Sub Binaryzation(Apath As String, Bpath As String)
        Dim pic As Bitmap = New Bitmap(Apath)
        Dim width As Integer = pic.Width
        Dim high As Integer = pic.Height
        For i = 0 To width - 1
            For j = 0 To high - 1
                Dim Color As Color = pic.GetPixel(i, j)
                If Color.R > 87 Or Color.G > 103 Or Color.B > 103 Then
                    pic.SetPixel(i, j, Drawing.Color.White)
                Else
                    pic.SetPixel(i, j, Drawing.Color.Black)
                End If
            Next
        Next
        pic.Save(Bpath, System.Drawing.Imaging.ImageFormat.Gif)
    End Sub
End Class
